package com.fate.system.utils;

import com.aspose.cells.Workbook;
import com.aspose.slides.*;
import com.aspose.words.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

public class FileTransformUtil {

  public static MultipartFile convertToPdf(MultipartFile file) throws Exception {
    String fileName = file.getOriginalFilename();
    if (fileName != null) {
      String extension = getFileExtension(fileName).toLowerCase();

      try (InputStream inputStream = file.getInputStream();
          ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

        switch (extension) {
          case "docx":
          case "doc":
            convertWordToPdf(inputStream, outputStream);
            break;
          case "xlsx":
          case "xls":
            convertExcelToPdf(inputStream, outputStream);
            break;
          case "pptx":
          case "ppt":
            convertPptToPdf(inputStream, outputStream);
            break;
          default:
            return file;
        }

        // 将转换后的PDF字节流转换为自定义的MultipartFile
        return new CustomMultipartFile(
            "file", // 参数名
            fileName.replace(extension, "pdf"), // 新文件名
            "application/pdf", // 文件类型
            outputStream.toByteArray() // PDF内容
            );
      }
    }
    throw new IllegalArgumentException("Invalid file name");
  }

  private static void convertWordToPdf(InputStream inputStream, OutputStream outputStream)
      throws Exception {

    Document document = new Document(inputStream);

    CompressWord.compress(document);

    document.save(outputStream, com.aspose.words.SaveFormat.PDF);
  }

  private static void convertExcelToPdf(InputStream inputStream, OutputStream outputStream)
      throws Exception {
    Workbook workbook = new Workbook(inputStream);
    workbook.save(outputStream, com.aspose.cells.SaveFormat.PDF);
  }

  private static void convertPptToPdf(InputStream inputStream, OutputStream outputStream)
      throws Exception {
    Presentation presentation = new Presentation(inputStream);
    Compress.removeUnusedMasterSlides(presentation);
    Compress.removeUnusedLayoutSlides(presentation);
    Compress.compressEmbeddedFonts(presentation);
    presentation.save(outputStream, com.aspose.slides.SaveFormat.Pdf);
  }

  public static String getFileExtension(String fileName) {
    if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
      return fileName.substring(fileName.lastIndexOf(".") + 1);
    } else {
      return "";
    }
  }
}
